package bbs.utils;

import bbs.entity.config.AppConfig;
import bbs.entity.constants.Constants;
import bbs.entity.dto.FileUploadDto;
import bbs.entity.enums.DateTimePatternEnum;
import bbs.entity.enums.FileUploadTypeEnum;
import bbs.exception.BusinessException;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import javax.annotation.Resource;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

@Component("fileUtils")
public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    @Resource
    private AppConfig appConfig;

    @Resource
    private ImageUtils imageUtils;

    public FileUploadDto uploadFile2Local(MultipartFile file, String folder, FileUploadTypeEnum typeEnum) {
        try {
            FileUploadDto uploadDto = new FileUploadDto();
            String originalFileName = file.getOriginalFilename();
            String fileSuffix = StringTools.getFileSuffix(originalFileName);
            if (originalFileName.length() > Constants.LENGTH_200)
                originalFileName = StringTools.getFileSuffix(originalFileName).substring(0, Constants.LENGTH_190) + fileSuffix;
            if (!ArrayUtils.contains((Object[])typeEnum.getSuffixArray(), fileSuffix))
                throw new BusinessException(Constants.FILE_TYPE_ERROR);

            String month = DateUtil.format(new Date(), DateTimePatternEnum.YYYYMM.getPattern());
            String baseFolder = this.appConfig.getProjectFolder() + "/file/";
            File targetFileFolder = new File(baseFolder + folder + month + "/");
            String fileName = StringTools.getRandomString(Constants.LENGTH_15) + fileSuffix;
            File targetFile = new File(targetFileFolder.getPath() + "/" + fileName);
            String localPath = month + "/" + fileName;
            if (typeEnum == FileUploadTypeEnum.AVATAR) {
                targetFileFolder = new File(baseFolder + Constants.FILE_FOLDER_AVATAR_NAME);
                targetFile = new File(targetFileFolder.getPath() + "/" + folder + Constants.AVATAR_SUFFIX);
                localPath = folder + Constants.AVATAR_SUFFIX;
            }

            if (!targetFileFolder.exists())
                targetFileFolder.mkdirs();

            file.transferTo(targetFile);

//            缩率图
            if (typeEnum == FileUploadTypeEnum.COMMENT_IMAGE) {
                String thumbnailName = targetFile.getName().replace(".", "_.");
                File thumbnail = new File(targetFile.getParent() + "/" + thumbnailName);
                Boolean thumbnailCreated = ImageUtils.createThumbnail(targetFile, Constants.LENGTH_200, Constants.LENGTH_200, thumbnail);
                if (!thumbnailCreated) {
                    FileUtils.copyFile(targetFile, thumbnail);
                }
            } else if (typeEnum == FileUploadTypeEnum.AVATAR || typeEnum == FileUploadTypeEnum.ARTICLE_COVER) {
                imageUtils.createThumbnail(targetFile, Constants.LENGTH_200, Constants.LENGTH_200, targetFile);
            }
            uploadDto.setLocalPath(localPath);
            uploadDto.setOriginalFileName(originalFileName);
            return uploadDto;
        } catch (BusinessException e) {
            logger.error(Constants.FILE_UPDATE_ERROR, (Throwable)e);
            throw e;
        } catch (Exception exception) {
            logger.error(Constants.FILE_UPDATE_ERROR, exception);
            throw new BusinessException(Constants.FILE_UPDATE_ERROR);
        }
    }
}
